const fs = require('fs');
const path = require('path');

class DatabaseMigration {
  constructor(db) {
    this.db = db;
    this.migrationsPath = path.join(__dirname, 'migrations');
  }

  // 检查数据库版本
  async getCurrentVersion() {
    return new Promise((resolve, reject) => {
      this.db.get(
        "SELECT config_value FROM app_config WHERE config_key = 'database_version'",
        (err, row) => {
          if (err) {
            // 如果表不存在，返回版本 0
            resolve('0.0');
          } else {
            resolve(row ? row.config_value : '0.0');
          }
        }
      );
    });
  }

  // 更新数据库版本
  async updateVersion(version) {
    return new Promise((resolve, reject) => {
      this.db.run(
        "INSERT OR REPLACE INTO app_config (config_key, config_value) VALUES ('database_version', ?)",
        [version],
        function(err) {
          if (err) {
            reject(err);
          } else {
            resolve(this.changes);
          }
        }
      );
    });
  }

  // 执行迁移文件
  async runMigration(sqlFilePath) {
    return new Promise((resolve, reject) => {
      if (!fs.existsSync(sqlFilePath)) {
        reject(new Error(`迁移文件不存在: ${sqlFilePath}`));
        return;
      }

      const sqlContent = fs.readFileSync(sqlFilePath, 'utf8');
      
      this.db.exec(sqlContent, (err) => {
        if (err) {
          reject(err);
        } else {
          resolve();
        }
      });
    });
  }

  // 执行所有迁移
  async migrate() {
    try {
      const currentVersion = await this.getCurrentVersion();
      console.log('当前数据库版本:', currentVersion);

      // 检查是否有迁移文件
      if (!fs.existsSync(this.migrationsPath)) {
        console.log('没有找到迁移文件目录');
        return;
      }

      const migrationFiles = fs.readdirSync(this.migrationsPath)
        .filter(file => file.endsWith('.sql'))
        .sort();

      for (const file of migrationFiles) {
        const version = file.replace('.sql', '');
        
        // 只执行比当前版本新的迁移
        if (this.compareVersions(version, currentVersion) > 0) {
          console.log(`执行迁移: ${file}`);
          
          const sqlFilePath = path.join(this.migrationsPath, file);
          await this.runMigration(sqlFilePath);
          
          // 更新版本号
          await this.updateVersion(version);
          console.log(`数据库版本更新为: ${version}`);
        }
      }

      console.log('数据库迁移完成');
    } catch (error) {
      console.error('数据库迁移失败:', error);
      throw error;
    }
  }

  // 比较版本号
  compareVersions(version1, version2) {
    const v1Parts = version1.split('.').map(Number);
    const v2Parts = version2.split('.').map(Number);
    
    for (let i = 0; i < Math.max(v1Parts.length, v2Parts.length); i++) {
      const v1Part = v1Parts[i] || 0;
      const v2Part = v2Parts[i] || 0;
      
      if (v1Part > v2Part) return 1;
      if (v1Part < v2Part) return -1;
    }
    
    return 0;
  }
}

module.exports = DatabaseMigration;
